
package com.heimali.happyreader.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.heimali.happyreader.R;
import com.heimali.happyreader.core.bean.Intro;

import java.util.ArrayList;
import java.util.List;

public class ArticleListAdapter extends BaseAdapter {
    private List<Intro> mArticleList = new ArrayList<Intro>();
    private LayoutInflater inflater;

    public ArticleListAdapter(Context context) {
        inflater = LayoutInflater.from(context);
    }

    public void insertOlder(List<Intro> list) {
        if (list != null) {
            mArticleList.addAll(list);
        }
    }

    public void insertLastest(List<Intro> list) {
        if (list != null) {
            mArticleList.addAll(0, list);
        }
    }

    public ArrayList<Intro> getDataSources() {
        return mArticleList != null ? (ArrayList<Intro>) mArticleList : new ArrayList<Intro>();
    }

    public void setDataSources(List<Intro> list) {
        if (list == null) {
            list = new ArrayList<Intro>();
        }
        mArticleList.clear();
        mArticleList.addAll(list);
    }

    public int getCount() {
        if (mArticleList == null) {
            return 0;
        }
        return mArticleList.size();
    }

    public Object getItem(int position) {
        if (mArticleList == null || position >= mArticleList.size() || position < 0) {
            return null;
        }
        return mArticleList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = new ViewHolder();
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.article_list_item, null);
            holder.time = (TextView) convertView.findViewById(R.id.article_item_time);
            holder.title = (TextView) convertView.findViewById(R.id.article_item_title);
            //holder.intro = (TextView) convertView.findViewById(R.id.article_item_intro);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Intro item = (Intro) getItem(position);
        holder.id = item.id;
        holder.time.setText(item.time);
        holder.title.setText(item.title);
        //holder.intro.setText(item.intro);
        return convertView;
    }

    public class ViewHolder {
        public int id;
        public TextView time;
        public TextView title;
        //public TextView intro;
    }
}
